import time from 'locutus/php/datetime/time';

const { action } = jinghuan.props;

/**
 * 车系
 */
class carscategory extends jinghuan.AdminController {


    _listModel(id = 0) {
        let model1 = this.db('jh_carscategory as a').leftJoin('jh_car_brand as b', 'b.id', 'a.brand_id')
            .select('a.*', 'b.name as brand')
            .where('a.status', '>', 0);

        if (id) {
            model1.where('a.id', id).first();
        }

        return model1;
    }
    /**
     *
     */
    @action({ auth: false, login: false })
    async datatable() {
        let model1 = this._listModel();

        let model2 = this.db('jh_carscategory as a')
            .where('a.status', '>', 0)
            .count('a.id as count');

        await this.default_datatable2(model1, model2, [])
    }

    /**
     * 
     */
    @action({ auth: false, login: false })
    async get_carscategory() {
        let data = await this.db('jh_carscategory')
            .select('id as value', 'name as title', 'brand_id as group')

        this.callback(data);
    }

    /**
     * 
     * @param {*} param0 
     * @param {*} param1 
     */
    @action({ auth: false })
    async do_add({ }, { name, code, brand_id }) {
        let model = await this.db('jh_carscategory')
            .insert({
                name,
                code,
                time: time(),
                u_time: time(),
                brand_id,
            });
        if (model) {
            this.record('添加车系成功');
            let data = await this._listModel(model[0]);

            this.callback(data, { toast: "message.success.add" });
        } else {
            this.record('添加车系失败');
            this.callback(false, { toast: "message.error.add" });
        }
    }


    /**
     * 
     * @param {*} GET 
     * @param {*} param1 
     */
    @action({ auth: false })
    async do_edit(GET, { name, code, id, brand_id }) {
        let model = await this.db('jh_carscategory')
            .where('id', '=', id)
            .update({
                name,
                code,
                u_time: time(),
                brand_id,
            });

        if (model) {
            this.record('编辑车系成功');
            let data = await this._listModel(id);

            this.callback(data, { toast: "message.success.edit" });
        } else {
            this.record('编辑车系失败');
            this.callback(false, { toast: "message.error.edit" });
        }
    }

}

export default carscategory;
